package com.shopping_back.controller;

import com.shopping_back.common.Result;
import com.shopping_back.pojo.dto.JoinGroupDTO;
import com.shopping_back.pojo.dto.OpenGroupDTO;
import com.shopping_back.pojo.vo.GroupbuyDetailVO;
import com.shopping_back.service.IGroupbuyService;
import com.shopping_back.util.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/groupbuy")
@RequiredArgsConstructor
public class GroupbuyController {

    private final IGroupbuyService groupbuyService;
    private final JwtUtils jwtUtils;

    /** 用户发起团购 */
    @PostMapping("/open")
    public Result open(HttpServletRequest request, @RequestBody @Valid OpenGroupDTO dto) {
        try {
            Long userId = jwtUtils.getCurrentUserId(request);
            Map<String, Object> map = groupbuyService.openGroup(dto, userId);
            return Result.success(map);
        } catch (IllegalArgumentException ex) {
            // service 中抛出的都是 IllegalArgumentException，这里 message 不同即可区分
            return Result.error(ex.getMessage());
        }
    }

    /** 通过邀请码参团 */

    @PostMapping("/join")
    public Result join(HttpServletRequest request,@RequestBody @Valid JoinGroupDTO dto) {
        try {
            Long userId = jwtUtils.getCurrentUserId(request);
            Map<String,Object> map = groupbuyService.joinGroupByCode(dto, userId);
            return Result.success(map);              // 包含 groupId 与 orderSn
        } catch (IllegalArgumentException ex) {
            return Result.error(ex.getMessage());
        } catch (Exception ex) {
            return Result.error("系统内部错误");
        }
    }


    /** 获取拼团详情（通过邀请码） */
    @GetMapping("/group/code/{inviteCode}")
    public Result detailByCode(@PathVariable String inviteCode) {
        try {
            return Result.success(groupbuyService.getGroupDetailByCode(inviteCode));
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("系统内部错误");
        }
    }

    /** 获取拼团详情（通过groupId） */
    @GetMapping("/group/{groupId}")
    public Result detail(@PathVariable Long groupId) {
        try {
            return Result.success(groupbuyService.getGroupDetail(groupId));
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return Result.error("系统内部错误");
        }
    }


    @GetMapping("/activity/{promotionId}")
    public Result detailByActivity(@PathVariable Long promotionId) {
        List<GroupbuyDetailVO> list = groupbuyService.getDetails(promotionId);
        return Result.success(list);
    }

}

